package com.newsnetwork.article.controller;

import com.newsnetwork.api.BaseController;
import com.newsnetwork.api.controller.article.ArticleControllerApi;
import com.newsnetwork.article.service.ArticleService;
import com.newsnetwork.enums.*;
import com.newsnetwork.grace.result.CommonJSONResult;
import com.newsnetwork.grace.result.ResponseStatusEnum;
import com.newsnetwork.pojo.ArticlePublicationStatus;
import com.newsnetwork.pojo.Category;
import com.newsnetwork.pojo.bo.NewArticleBO;
import com.newsnetwork.utils.JsonUtils;
import com.newsnetwork.utils.PagedGridResult;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;


import javax.validation.Valid;

import java.io.IOException;
import java.util.*;

/**
 * @author DingNing
 * @date 2022/11/10 22:50
 * @Description:
 */
@RestController
public class ArticleController extends BaseController implements ArticleControllerApi {

    final static Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;


    @Override
    public CommonJSONResult createArticle(@Valid NewArticleBO newArticleBO) {

//        // 1.判断BindingResult是否保存错误的验证信息，如果有，则直接return
//        if (result.hasErrors()) {
//            Map<String, String> errorMap = getErrors(result);
//            return CommonJSONResult.errorMap(errorMap);
//        }

        // 2.判断文章封面类型，单图必填，纯文字则设置为空
        if (newArticleBO.getArticleType() == ArticleCoverType.ONE_IMAGE.type) {
            if (StringUtils.isBlank(newArticleBO.getArticleCover())) {
                return CommonJSONResult.errorCustom(ResponseStatusEnum.ARTICLE_COVER_NOT_EXIST_ERROR);
            }
        } else if (newArticleBO.getArticleType() == ArticleCoverType.WORDS.type) {
            // 如果为纯文字，则ArticleCover设置为空
            newArticleBO.setArticleCover("");
        }

        // 3.判断分类id是否存在
        String allCatJson = redisOperator.get(REDIS_ALL_CATEGORY);
        Category temp = null;
        if (StringUtils.isBlank(allCatJson)) {
            return CommonJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_OPERATION_ERROR);
        } else {
            List<Category> catList = JsonUtils.jsonToList(allCatJson, Category.class);
            for (Category c : catList) {
                if(c.getId() == newArticleBO.getCategoryId()) {
                    temp = c;
                    break;
                }
            }
            if (temp == null) {
                return CommonJSONResult.errorCustom(ResponseStatusEnum.ARTICLE_CATEGORY_NOT_EXIST_ERROR);
            }
        }


        ArticlePublicationStatus article = articleService.createArticle(newArticleBO, temp);

        String articleId = article.getArticleId();
        String articleStatus = article.getArticleStatus();
        if (articleStatus.equalsIgnoreCase(ArticleReviewLevel.PASS.type)
                && newArticleBO.getIsAppoint() == ArticleAppointType.IMMEDIATELY.type) {
            // 审核文章成功并且是立即发布, 生成文章详情页静态html
            try {
                //createArticleHTML(articleId);
                articleService.updateArticleToGridFS(articleId);
            } catch (IOException | TemplateException e) {
                e.printStackTrace();
            }
        }
        return CommonJSONResult.ok();
    }

    @Override
    public CommonJSONResult queryMyList(String userId,
                                        String keyword,
                                        Integer status,
                                        Date startDate,
                                        Date endDate,
                                        Integer page,
                                        Integer pageSize) {
        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.errorCustom(ResponseStatusEnum.ARTICLE_QUERY_PARAMS_ERROR);
        }

        if (page == null) {
            page = COMMON_START_PAGE;
        }
        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        // 查询我的列表，调用service
        PagedGridResult grid = articleService.queryMyArticleList(userId,
                keyword,
                status,
                startDate,
                endDate,
                page,
                pageSize);

        return CommonJSONResult.ok(grid);
    }

    @Override
    public CommonJSONResult queryAllList(Integer status, Integer page, Integer pageSize) {
        if (page == null) {
            page = COMMON_START_PAGE;
        }
        if (pageSize == null) {
            page = COMMON_PAGE_SIZE;
        }
        PagedGridResult gridResult = articleService.queryAllArticleListAdmin(status, page, pageSize);
        return CommonJSONResult.ok(gridResult);
    }

    @Override
    public CommonJSONResult doReview(String articleId, Integer passOrNot) {

        Integer pendingStatus;
        if (passOrNot == YesOrNo.YES.type) {
            // 审核成功
            pendingStatus = ArticleReviewStatus.SUCCESS.type;
        } else if (passOrNot == YesOrNo.NO.type) {
            // 审核失败
            pendingStatus = ArticleReviewStatus.FAILED.type;
        } else {
            return CommonJSONResult.errorCustom(ResponseStatusEnum.ARTICLE_REVIEW_ERROR);
        }

        // 保存到数据库，更改文章的状态为审核成功或者失败
        articleService.updateArticleStatus(articleId, pendingStatus);
        // 查询文章发布状态
        int appoint = articleService.queryArticleAppoint(articleId);
        // 审核文章成功并且是立即发布, 生成文章详情页静态html
        if (pendingStatus == ArticleReviewStatus.SUCCESS.type && appoint == ArticleAppointType.IMMEDIATELY.type) {
            try {
                //createArticleHTML(articleId);
                articleService.updateArticleToGridFS(articleId);
            } catch (IOException | TemplateException e) {
                e.printStackTrace();
            }
        }

        return CommonJSONResult.ok();
    }

    @Override
    public CommonJSONResult delete(String userId, String articleId) {
        articleService.deleteArticle(userId, articleId);
        return CommonJSONResult.ok();
    }

    @Override
    public CommonJSONResult withdraw(String userId, String articleId) {
        articleService.withdrawArticle(userId, articleId);
        return CommonJSONResult.ok();
    }
}
